package com.example.javacore.listmap;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tiger
 */
public class MapUtil {

    public static Map<String, Object> initMap() {
        Map<String, Object> item = new HashMap<>(16);
        item.put("id", "1");
        item.put("name", "语文");
        item.put("age", 80);
        item.put("score", 99.9);
        item.put("birthday", "2000-01-01");
        return item;
    }

    public static List<Map<String, Object>> initMapList() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> item = new HashMap<>(16);
        item.put("id", "1");
        item.put("name", "李白");
        item.put("date", DateUtil.parseLocalDateTime("2022-11-01 11:11:11"));
        item.put("age", 22);
        item.put("score", 20.2);
        mapList.add(item);
        item = new HashMap<>(16);
        item.put("id", "2");
        item.put("name", "王五");
        item.put("date", DateUtil.parseLocalDateTime("2022-10-01 12:21:11"));
        item.put("age", 20);
        item.put("score", 21.22);
        mapList.add(item);
        return mapList;
    }

    /**
     * 计算
     */
    public static void calculation() {
        List<Map<String, Object>> mapList = initMapList();
        System.out.println("和:" + mapList.stream().mapToInt(m -> (int) m.get("age")).sum());
        System.out.println("最小值:" + mapList.stream().mapToInt(m -> (int) m.get("age")).min());
        System.out.println("最大值:" + mapList.stream().mapToInt(m -> (int) m.get("age")).max());
    }

    public static void sortByValue() {
        List<Map<String, Object>> mapList = initMapList();
        System.out.println("排序前:" + JSON.toJSONString(mapList));

        mapList = mapList.stream().sorted(Comparator.comparing(i -> ((int) i.get("age")))).collect(Collectors.toList());
        System.out.println("正向整数排序:" + JSON.toJSONString(mapList));
        mapList = mapList.stream().sorted((i, j) -> (((Integer) j.get("age")).compareTo(((Integer) i.get("age"))))).collect(Collectors.toList());
        System.out.println("反向整数排序:" + JSON.toJSONString(mapList));

        mapList = mapList.stream().sorted(Comparator.comparing(i -> ((LocalDateTime) i.get("date")))).collect(Collectors.toList());
        System.out.println("正向时间排序:" + JSON.toJSONString(mapList));
        mapList = mapList.stream().sorted((i, j) -> (((LocalDateTime) j.get("date")).compareTo(((LocalDateTime) i.get("date"))))).collect(Collectors.toList());
        System.out.println("反向时间排序:" + JSON.toJSONString(mapList));

    }

}
